from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from ..models.employee import Employee as EmployeeModel
from ..models.department import Department
from ..schemas.employee import EmployeeCreate, EmployeeUpdate
from fastapi import HTTPException, status
from datetime import datetime

class EmployeeService:
    def __init__(self, db: Session):
        self.db = db

    def get_employees(self, skip: int = 0, limit: int = 100) -> List[EmployeeModel]:
        """获取员工列表"""
        return self.db.query(EmployeeModel).offset(skip).limit(limit).all()

    def get_employee(self, employee_id: int) -> Optional[EmployeeModel]:
        """根据ID获取员工"""
        return self.db.query(EmployeeModel).filter(EmployeeModel.id == employee_id).first()

    def get_employee_by_code(self, employee_code: str) -> Optional[EmployeeModel]:
        """根据员工编号获取员工"""
        return self.db.query(EmployeeModel).filter(EmployeeModel.employee_code == employee_code).first()

    def get_employee_by_email(self, email: str) -> Optional[EmployeeModel]:
        """根据邮箱获取员工"""
        return self.db.query(EmployeeModel).filter(EmployeeModel.email == email).first()

    def create_employee(self, employee_data: EmployeeCreate) -> EmployeeModel:
        """创建员工"""
        # 检查员工编号是否已存在
        existing_employee = self.get_employee_by_code(employee_data.employee_code)
        if existing_employee:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="员工编号已存在"
            )
        
        # 检查邮箱是否已存在
        existing_employee = self.get_employee_by_email(employee_data.email)
        if existing_employee:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已存在"
            )
        
        # 检查部门是否存在
        department = self.db.query(Department).filter(Department.id == employee_data.department_id).first()
        if not department:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="部门不存在"
            )
        
        # 创建新员工
        db_employee = EmployeeModel(**employee_data.dict())
        try:
            self.db.add(db_employee)
            self.db.commit()
            self.db.refresh(db_employee)
            return db_employee
        except IntegrityError:
            self.db.rollback()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="创建员工失败，数据完整性错误"
            )

    def update_employee(self, employee_id: int, employee_data: EmployeeUpdate) -> EmployeeModel:
        """更新员工信息"""
        db_employee = self.get_employee(employee_id)
        if not db_employee:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="员工不存在"
            )
        
        # 如果更新了员工编号，检查是否已存在
        if employee_data.employee_code and employee_data.employee_code != db_employee.employee_code:
            existing_employee = self.get_employee_by_code(employee_data.employee_code)
            if existing_employee:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="员工编号已存在"
                )
        
        # 如果更新了邮箱，检查是否已存在
        if employee_data.email and employee_data.email != db_employee.email:
            existing_employee = self.get_employee_by_email(employee_data.email)
            if existing_employee:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已存在"
                )
        
        # 如果更新了部门，检查部门是否存在
        if employee_data.department_id and employee_data.department_id != db_employee.department_id:
            department = self.db.query(Department).filter(Department.id == employee_data.department_id).first()
            if not department:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="部门不存在"
                )
        
        # 更新员工信息
        for key, value in employee_data.dict(exclude_unset=True).items():
            setattr(db_employee, key, value)
        
        self.db.commit()
        self.db.refresh(db_employee)
        return db_employee

    def delete_employee(self, employee_id: int) -> None:
        """删除员工"""
        db_employee = self.get_employee(employee_id)
        if not db_employee:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="员工不存在"
            )
        
        self.db.delete(db_employee)
        self.db.commit()

    def get_employees_by_department(self, department_id: int) -> List[EmployeeModel]:
        """根据部门获取员工列表"""
        # 检查部门是否存在
        department = self.db.query(Department).filter(Department.id == department_id).first()
        if not department:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        
        return self.db.query(EmployeeModel).filter(EmployeeModel.department_id == department_id).all()

    def get_employee_work_age(self, employee_id: int) -> dict:
        """获取员工工龄信息"""
        db_employee = self.get_employee(employee_id)
        if not db_employee:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="员工不存在"
            )
        
        # 计算工龄
        hire_date = db_employee.hire_date
        today = datetime.now().date()
        
        # 计算年数
        years = today.year - hire_date.year
        
        # 检查是否已过当年的入职月份和日期
        if (today.month, today.day) < (hire_date.month, hire_date.day):
            years -= 1
        
        # 计算总天数
        total_days = (today - hire_date).days
        
        return {
            "employee_id": employee_id,
            "employee_name": db_employee.full_name,
            "hire_date": hire_date,
            "years": years,
            "total_days": total_days
        }